package me.younian.transmit;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;

public class SocketClient {
    // 搭建客户端
    public static void main(String[] args) throws IOException {
        try {
            // 1、创建客户端Socket，指定服务器地址和端口
            // Socket socket=new Socket("127.0.0.1",5200);
            Socket socket = new Socket("127.0.0.1", 5209);

            System.out.println("客户端启动成功");
            while (true) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // GET /test.jpg /HTTP1.1
                String line = reader.readLine();
                String resource = line.substring(line.indexOf('/'), line.lastIndexOf('/') - 5);
                resource = URLDecoder.decode(resource, "UTF-8");
                System.out.println("req : " + resource);
                //System.out.println(new String(data));
                String res = HttpRequest.sendGet("http://localhost" + resource);
                res += "##EOF##";
                System.out.println("return size (/1024) : " + res.length() / 1024);
                socket.getOutputStream().write(res.getBytes());
                socket.getOutputStream().flush();
                //阻塞不能关闭
                //socket.shutdownOutput();
                //socket.getOutputStream().close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}